import { defineStore } from 'pinia';
import { setToken, getToken, removeToken } from '@/utils/auth';
import { login as userLogin, logout as userLogout } from '@/api/user';

export const useUserStore = defineStore('user-store', {
	state: () => {
		return {
			token: getToken(),
			userInfo: null,
		};
	},
	getters: {},
	actions: {
		// Reset user's information
		resetInfo() {
			this.$reset();
		},
		// Login
		async login(loginForm) {
			try {
				const res = await userLogin(loginForm);
				this.token = res.data.token;
				setToken(res.data.token);
			} catch (error) {
				this.token = null;
				removeToken();
				throw error;
			}
		},
		logoutCallBack() {
			this.resetInfo();
			removeToken();
		},
		// Logout
		async logout() {
			try {
				await userLogout();
			} finally {
				this.logoutCallBack();
			}
		},
	},
	// 开启数据缓存
	persist: {
		enabled: true,
		strategies: [
			{
				storage: localStorage, // 指定本地缓存的类型
				paths: [], // 指定本地缓存的字段
			},
		],
	},
});
